<template>
  <div v-loading="loading" element-loading-text="加载中..." class="new_sla">
    <div class="header">
      <div class="title">
        <template v-if="slaData.id">
          <span class="text">编辑SLA</span>
          <HStatus v-if="!slaData?.status">启用</HStatus>
          <HStatus v-else type="info">禁用</HStatus>
        </template>
        <span v-else class="text">新建SLA</span>
      </div>
      <div class="btn_group">
        <HPlainButton @click="onSave">保存</HPlainButton>
        <h-button @click="onCancel">取消</h-button>
      </div>
    </div>
    <div ref="basicInfoRef" class="basic_info">
      <div class="title">基本信息</div>
      <el-form
        ref="ruleFormRef"
        :model="slaData"
        :rules="slaDataRules"
        label-width="70"
        inline-message
      >
        <div class="form_item_container">
          <el-form-item label="SLA名称" prop="name">
            <el-input v-model.trim="slaData.name" clearable placeholder="请输入SLA名称" />
          </el-form-item>
          <el-form-item label="适用模块" prop="moduleIds">
            <el-select
              v-model="slaData.moduleIds"
              :remote-method="changmoduleList"
              clearable
              collapse-tags-tooltip
              filterable
              collapse-tags
              multiple
              placeholder="请选择"
              remote
              remote-show-suffix
            >
              <el-option
                v-for="(item, index) in moduleList"
                :key="index"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </div>
        <div class="form_item_container">
          <el-form-item label="生效时间" prop="dateType">
            <el-select v-model="slaData.dateType" placeholder="请选择">
              <el-option :value="1" label="全天" />
              <el-option :value="2" label="时间范围" />
            </el-select>
          </el-form-item>
          <el-form-item
            v-if="slaData.dateType === 2"
            label="时间范围"
            prop="endTime"
            class="time_range"
          >
            <el-time-select
              v-model="slaData.startTime"
              :max-time="slaData.endTime"
              class="reservationTime-el-time-select"
              end="22:00"
              placeholder="开始时间"
              size="small"
              start="06:00"
              step="1:00"
            />
            <span class="reservationTime-span">~</span>
            <el-time-select
              v-model="slaData.endTime"
              :min-time="slaData.startTime"
              class="reservationTime-el-time-select"
              end="22:00"
              placeholder="结束时间"
              size="small"
              start="06:00"
              step="1:00"
            />
          </el-form-item>
          <el-form-item label="描述">
            <el-input
              v-model.trim="slaData.remark"
              clearable
              placeholder="可输入描述"
              type="textarea"
              resize="both"
              maxlength="200"
              show-word-limit
              autosize
            />
          </el-form-item>
        </div>
        <div class="form_item_container">
          <el-form-item label="提醒方式" prop="remindMode">
            <el-select v-model="slaData.remindMode" multiple placeholder="请选择">
              <el-option
                v-for="(item, index) in remindModeList"
                :key="index"
                :label="item.name"
                :value="item.val"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="SLA状态">
            <el-radio-group v-model="slaData.status">
              <el-radio :value="false">启用</el-radio>
              <el-radio :value="true">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <div class="trigger_condition" :style="triggerConditionStyle">
      <div class="title">触发条件</div>
      <div class="table">
        <el-table
          :border="true"
          :data="slaData.slaConditionVos"
          min-height="200px"
          height="100%"
          resizable
          stripe
        >
          <template #empty>
            <el-empty description="暂无数据" />
          </template>
          <el-table-column fixed label="序号" type="index" width="60" :align="'center'" />
          <el-table-column label="触发条件" show-overflow-tooltip width="170">
            <template #default="i">
              <el-select v-model="i.row.type" @change="changeType(i.row.type, i.$index)">
                <el-option
                  v-for="(item, index) in typeList"
                  :key="index"
                  :disabled="isStop(item.val)"
                  :label="item.name"
                  :value="item.val"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="节点时效" width="240">
            <template #header>
              节点时效
              <el-popover
                ref="popoverEnabledAll"
                :width="160"
                placement="top-start"
                trigger="click"
              >
                <h5 style="margin-bottom: 10px">批量开启/关闭</h5>
                <div style="display: flex; align-items: center; gap: 7px; white-space: nowrap">
                  <el-switch v-model="enabledAll" inline-prompt />
                  <span v-if="enabledAll">开启</span>
                  <span v-else>关闭</span>
                </div>
                <p style="font-size: 12px; color: #999">不开启则该节点不生效</p>
                <div style="display: flex; justify-content: end; margin-top: 10px">
                  <el-button
                    color="#007cff"
                    style="padding: 0 4px; height: 20px"
                    @click="changeEnabledAll"
                    >确定</el-button
                  >
                </div>
                <template #reference>
                  <span
                    style="font-size: 11px; background-color: #fff; cursor: pointer; color: #007cff"
                    >批量</span
                  >
                </template>
              </el-popover>
            </template>
            <template #default="i">
              <div style="display: flex; align-items: center">
                <div style="display: flex; align-items: center; gap: 7px; white-space: nowrap">
                  <el-switch v-model="i.row.enabled" inline-prompt />
                  <span v-if="i.row.enabled">开启</span>
                  <span v-else>关闭</span>
                </div>
                <el-input
                  v-model.trim="i.row.ageingTime"
                  :disabled="!i.row.enabled"
                  placeholder="时效"
                  style="margin-left: 10px"
                  @input="i.row.ageingTime = i.row.ageingTime.replace(/[^0-9]/g, '')"
                >
                  <template #append>小时</template>
                </el-input>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="提醒条件" show-overflow-tooltip width="120">
            <template #default="i">
              <div style="display: flex; align-items: center; gap: 7px">
                <el-switch
                  v-model="i.row.enableBeforeOverTimeRemind"
                  :disabled="!i.row.enabled"
                  inline-prompt
                />
                <span :style="{ color: i.row.disabled ? '#333' : '#999' }">超时前</span>
              </div>
              <span style="display: flex; align-items: center; gap: 7px">
                <el-switch
                  v-model="i.row.enableAfterOverTimeRemind"
                  :disabled="!i.row.enabled"
                  inline-prompt
                />
                <span :style="{ color: i.row.disabled ? '#333' : '#999' }">超时后</span>
              </span>
            </template>
          </el-table-column>
          <el-table-column label="提醒时间" show-overflow-tooltip width="220">
            <template #default="i">
              <el-input
                v-if="i.row.enableBeforeOverTimeRemind"
                v-model.trim="i.row.beforeOverTimeRemindTime"
                :disabled="!i.row.enabled"
                placeholder="超时前提醒时间"
                @input="
                  i.row.beforeOverTimeRemindTime = i.row.beforeOverTimeRemindTime.replace(
                    /[^0-9]/g,
                    '',
                  )
                "
              >
                <template #prepend>每 </template>
                <template #append>小时</template>
              </el-input>
              <br v-if="i.row.enableBeforeOverTimeRemind" />
              <el-input
                v-if="i.row.enableAfterOverTimeRemind"
                v-model.trim="i.row.afterOverTimeRemindTime"
                :disabled="!i.row.enabled"
                placeholder="超时后提醒时间"
                style="margin-top: 5px"
                @input="
                  i.row.afterOverTimeRemindTime = i.row.afterOverTimeRemindTime.replace(
                    /[^0-9]/g,
                    '',
                  )
                "
              >
                <template #prepend>每 </template>
                <template #append>小时</template>
              </el-input>
            </template>
          </el-table-column>

          <el-table-column label="提醒对象类型" min-width="150" show-overflow-tooltip>
            <template #default="i">
              <el-select
                v-if="i.row.enableBeforeOverTimeRemind"
                v-model="i.row.beforeOverTimeRemindEmpType"
                :disabled="!i.row.enabled"
                multiple
                collapse-tags-tooltip
                filterable
                collapse-tags
                placeholder="提醒对象类型"
                style="width: 100%"
                :max-collapse-tags="1"
              >
                <el-option
                  v-for="(item, index) in OverTimeRemindEmpType"
                  :key="index"
                  :disabled="OverTimeRemindEmpTypeScl(i.row.type, item.val)"
                  :label="item.name"
                  :value="item.val"
                ></el-option>
              </el-select>
              <br v-if="i.row.enableBeforeOverTimeRemind" />
              <el-select
                v-if="i.row.enableAfterOverTimeRemind"
                v-model="i.row.afterOverTimeRemindEmpType"
                :disabled="!i.row.enabled"
                multiple
                collapse-tags-tooltip
                filterable
                collapse-tags
                placeholder="提醒对象类型"
                style="margin-top: 5px; width: 100%"
                :max-collapse-tags="1"
              >
                <el-option
                  v-for="(item, index) in OverTimeRemindEmpType"
                  :key="index"
                  :disabled="OverTimeRemindEmpTypeScl(i.row.type, item.val)"
                  :label="item.name"
                  :value="item.val"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="提醒对象" min-width="150" show-overflow-tooltip>
            <template #default="i">
              <el-select
                v-if="
                  i.row.enableBeforeOverTimeRemind &&
                  i.row.beforeOverTimeRemindEmpType.includes('2')
                "
                v-model="i.row.slaBeforeOverTimeRemindEmpIds"
                :disabled="!i.row.enabled"
                multiple
                collapse-tags-tooltip
                filterable
                collapse-tags
                placeholder="超时前提醒对象"
                style="width: 100%"
              >
                <el-option
                  v-for="(item, index) in i.row.customersData"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
              <br v-if="i.row.enableBeforeOverTimeRemind" />
              <el-select
                v-if="i.row.enableAfterOverTimeRemind"
                v-model="i.row.slaAfterOverTimeRemindEmpIds"
                :disabled="!i.row.enabled"
                :style="`margin-top: 5px;width: 100%;opacity: ${
                  i.row.enableAfterOverTimeRemind && i.row.afterOverTimeRemindEmpType.includes('2')
                    ? '1'
                    : '0'
                };`"
                multiple
                collapse-tags-tooltip
                filterable
                collapse-tags
                placeholder="超时后提醒对象"
              >
                <el-option
                  v-for="(item, index) in i.row.customersData"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="90" fixed="right">
            <template #default="scope">
              <el-space :size="0" :spacer="spacer">
                <h-link
                  v-if="slaData.slaConditionVos.length > 1"
                  type="error"
                  @click="detelePro(scope.$index)"
                  >删除</h-link
                >
                <h-link v-if="scope.$index === 0" @click="addGoodsList">添加</h-link>
              </el-space>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { CSSProperties, h, onMounted, ref, watch } from 'vue'
  import { ElDivider, ElMessage } from 'element-plus'
  import { workModulePageSelect } from '../../../api/order'
  import { getBeforeEditData, SaveSLA } from '../../../api/sla'
  import { empPageSelecct } from '../../../api/organize'
  import { useRoute, useRouter } from 'vue-router'
  import { useTagsViewStore } from '@/store/modules/tagsView'
  import routeComponentName from '@/config/route-component-name'

  defineOptions({
    name: routeComponentName.setting.slaFormSet,
  })

  // 间距组件的间隔符
  const spacer = h(ElDivider, {
    direction: 'vertical',
    style: 'display: flex; align-items: center;',
  })

  const basicInfoHeight = ref(145)
  const basicInfoRef = ref<HTMLDivElement | null>(null)
  const triggerConditionStyle = ref<CSSProperties>({
    height: '200px',
  })

  const basicInfoResizeObserver = new ResizeObserver((entries) => {
    for (const entry of entries) {
      basicInfoHeight.value = entry.borderBoxSize[0].blockSize
    }
    setTriggerConditionHeight()
  })

  const setTriggerConditionHeight = () => {
    triggerConditionStyle.value.height = `calc(100% - 24px - 52px - ${basicInfoHeight.value}px)`
  }

  const startWatchBasicInfoHeight = () => {
    if (basicInfoRef.value) {
      basicInfoResizeObserver.observe(basicInfoRef.value)
    }
  }

  const TagsViewStore = useTagsViewStore()
  const router = useRouter()
  const route = useRoute()
  const slaData = ref({
    dateType: 1, //生效时间类型：1-全天，2-时间范围,示例值(1)
    endTime: '',
    startTime: '',
    id: null,
    moduleIds: [], //模块ID集合
    name: '',
    remark: '',
    remindMode: ['3'], //	提醒方式：1-系统消息，2-微信，3-短信，支持多选,示例值([ "3" ])
    slaConditionVos: [
      ////	SLA触发条件集合对象
      {
        afterOverTimeRemindEmpType: [],
        afterOverTimeRemindTime: 0, //超时后提醒时间，单位小时
        ageingTime: 1, //时效，单位小时，当ienabled=true时生效
        beforeOverTimeRemindEmpType: [],
        beforeOverTimeRemindTime: 0, //超时前提醒时间，单位小时
        enableAfterOverTimeRemind: false, //是否启用超时后提醒：false-不启用，true-启用
        enableBeforeOverTimeRemind: false, //是否启用超时前提醒：false-不启用，true-启用
        enabled: false, //是否开启节点时效：false-不开启，true-开启
        id: null,
        slaAfterOverTimeRemindEmpIds: [], //超时后提醒指定人员ID对象
        slaBeforeOverTimeRemindEmpIds: [], //超时前提醒指定人员ID对象
        type: null, //触发条件类型
        customersData: [],
      },
    ],
    status: false, //SLA状态：false-启用，true-禁用
  })
  const moduleList: any = ref([])
  const ruleFormRef = ref()
  const StartEenTime = () => {
    return (rule: any, value: string, callback: any) => {
      if (!(slaData.value.endTime && slaData.value.startTime)) {
        callback(new Error('请选择时间范围'))
      } else {
        callback()
      }
    }
  }
  const slaDataRules = ref({
    name: [{ required: true, message: '请输入SLA名称', trigger: ['blur', 'change'] }],
    moduleIds: [{ required: true, message: '适用模块', trigger: ['blur', 'change'] }],
    remindMode: [{ required: true, message: '提醒方式', trigger: ['blur', 'change'] }],
    dateType: [{ required: true, message: '生效时间', trigger: ['blur', 'change'] }],
    endTime: [
      { required: true, message: '时间范围', trigger: ['blur', 'change'] },
      {
        validator: StartEenTime(),
        trigger: 'blur',
      },
    ],
  })

  const remindModeList = ref([
    { name: '系统消息', val: '1' },
    { name: '微信', val: '2' },
    { name: '短信', val: '3' },
  ])
  //超时前、后提醒人员
  const OverTimeRemindEmpType = ref([
    { name: '工单客服', val: '1' },
    { name: '指定人员', val: '2' },
    { name: '网点负责人', val: '3' },
    { name: '工程师', val: '4' },
  ])
  //触发条件类型
  const typeList = ref([
    { name: '未分配客服', val: 1 },
    { name: '未派单', val: 2 },
    { name: '网点未接单', val: 3 },
    { name: '工程师未接单', val: 4 },
    { name: '工程师未拨打电话', val: 5 },
    { name: '工程师未预约', val: 6 },
    { name: '工程师未签到', val: 7 },
  ])
  const loading = ref(false)

  //获取工单模块
  const workModulePageSelectList = () => {
    let data = {
      name: valName.value, //SLA名称
      page: 0, //当面页码
      limit: 0, //每页显示数量
    }
    workModulePageSelect(data).then((res) => {
      moduleList.value = res.data.data.rows
    })
  }
  const valName = ref('')
  const changmoduleList = (val) => {
    valName.value = val
  }
  const getBeforeEdit = async (id) => {
    await getBeforeEditData(id).then((res) => {
      if (res) {
        slaData.value = res.data.data.row
      }
    })
  }
  // 触发条件不能重复
  const isStop = (val) => {
    let arr = []
    arr = slaData.value.slaConditionVos.map((o) => {
      return o.type
    })
    return arr.includes(val)
  }
  // 根据触发条件可选人员类型
  const OverTimeRemindEmpTypeScl = (type, val) => {
    switch (type) {
      case 1:
        if (val != '2') {
          return true
        }
        break
      case 2:
        if (val == '3' || val == '4') {
          return true
        }
        break
      case 3:
        if (val == '4') {
          return true
        }
        break
    }
  }
  // 获取客服
  const getworkTeamPageSelect = (val, index) => {
    // 仅当缓存中没有数据时才触发请求
    let data = {
      limit: 0,
      name: val,
      page: 0,
    }
    empPageSelecct(data).then((res) => {
      if (res.data.success) {
        slaData.value.slaConditionVos[index].customersData = res.data.data.rows
      }
    })
  }
  // 触发条件改变时 人员类型重新选择
  const changeType = (type, index) => {
    slaData.value.slaConditionVos = slaData.value.slaConditionVos.map((o, i) => {
      if (i == index) {
        switch (type) {
          case 1:
            o.beforeOverTimeRemindEmpType = o.beforeOverTimeRemindEmpType.filter((i) => i == '2')
            o.afterOverTimeRemindEmpType = o.afterOverTimeRemindEmpType.filter((i) => i == '2')
            break
          case 2:
            o.beforeOverTimeRemindEmpType = o.beforeOverTimeRemindEmpType.filter(
              (i) => i == '1' || i == '2',
            )
            o.afterOverTimeRemindEmpType = o.afterOverTimeRemindEmpType.filter(
              (i) => i == '1' || i == '2',
            )
            break
          case 3:
            o.beforeOverTimeRemindEmpType = o.beforeOverTimeRemindEmpType.filter((i) => i != '4')
            o.afterOverTimeRemindEmpType = o.afterOverTimeRemindEmpType.filter((i) => i != '4')
            break
        }
      }
      return o
    })
  }
  // 批量开启/关闭
  const enabledAll = ref(false)
  const popoverEnabledAll = ref()
  const changeEnabledAll = () => {
    slaData.value.slaConditionVos = slaData.value.slaConditionVos.map((o) => {
      o.enabled = enabledAll.value
      return o
    })
    popoverEnabledAll.value.hide()
  }
  //添加
  const addGoodsList = () => {
    slaData.value.slaConditionVos.push({
      afterOverTimeRemindEmpType: [], //超时后提醒人员类型：1-工单客服，2-指定人员，3-网点负责人，4-工程师,示例值([ "2" ])
      afterOverTimeRemindTime: null, //超时后提醒时间，单位小时
      ageingTime: 1, //时效，单位小时，当ienabled=true时生效
      beforeOverTimeRemindEmpType: [], //超时前提醒人员类型：1-工单客服，2-指定人员，3-网点负责人，4-工程师,示例值([ "2" ])
      beforeOverTimeRemindTime: null, //超时前提醒时间，单位小时
      enableAfterOverTimeRemind: false, //是否启用超时后提醒：false-不启用，true-启用
      enableBeforeOverTimeRemind: false, //是否启用超时前提醒：false-不启用，true-启用
      enabled: false, //是否开启节点时效：false-不开启，true-开启
      id: null,
      slaAfterOverTimeRemindEmpIds: [], //超时后提醒指定人员ID对象
      slaBeforeOverTimeRemindEmpIds: [], //超时前提醒指定人员ID对象
      type: null, //触发条件类型
      customersData: [],
    })
    getworkTeamPageSelect('', slaData.value.slaConditionVos.length - 1)
  }

  //删除
  const detelePro = (index) => {
    if (slaData.value.slaConditionVos.length == 1) {
      ElMessage({
        message: '至少保留一条',
        showClose: true,
        plain: true,
        type: 'warning',
        duration: 5000,
      })
      return
    }
    slaData.value.slaConditionVos.splice(index, 1)
  }
  // 保存
  const onSave = async () => {
    if (!ruleFormRef.value) return
    await ruleFormRef.value.validate(async (valid, fields) => {
      if (valid) {
        let isTrue = slaData.value.slaConditionVos.every((o) => {
          return (
            o.ageingTime >= o.afterOverTimeRemindTime && o.ageingTime >= o.beforeOverTimeRemindTime
          )
        })
        if (!isTrue) {
          ElMessage({
            showClose: true,
            message: '提醒时间不能大于节点时效',
            duration: 5000,
            type: 'warning',
            plain: true,
          })
        } else {
          loading.value = true
          await SaveSLA(slaData.value).then((res) => {
            if (res) {
              ElMessage({
                showClose: true,
                message: res.data.message,
                duration: 5000,
                type: res.data.success ? 'success' : 'error',
                plain: true,
              })
              if (res.data.success) {
                ruleFormRef.value.resetFields()
                TagsViewStore.delView(route.path)
                router.push({ path: '/busic/base/orderset', query: { active: 'OrderSLA' } })
              }
            }
          })
          loading.value = false
        }
      }
    })
  }
  // 取消
  const onCancel = () => {
    if (!ruleFormRef.value) return
    ruleFormRef.value.resetFields()
    TagsViewStore.delView(route.path)
    router.push({ path: '/busic/base/orderset', query: { active: 'OrderSLA' } })
  }

  watch(valName, (n) => {
    workModulePageSelectList()
  })

  watch(
    () => slaData.value.dateType,
    (n) => {
      if (n == 1) {
        slaData.value.endTime = ''
        slaData.value.startTime = ''
      }
    },
  )

  watch(
    () => TagsViewStore.getReloadPages,
    (value) => {
      if (value.includes(route.path)) {
        basicInfoResizeObserver.disconnect()
      }
    },
    { immediate: true, deep: true },
  )

  onMounted(async () => {
    loading.value = true
    if (route.params.id) {
      await getBeforeEdit(route.params.id)
    }
    workModulePageSelectList()
    slaData.value.slaConditionVos.map((o, index) => {
      getworkTeamPageSelect('', index)
    })
    loading.value = false
    startWatchBasicInfoHeight()
  })
</script>
<style lang="scss" scoped>
  @import './index';

  :deep(.el-input .el-input__wrapper) {
    height: auto !important;
  }
</style>
